//
//  TDDiscoverSearchView.swift
//  微博
//
//  Created by tong dan on 16/2/29.
//  Copyright © 2016年 tong dan. All rights reserved.
//

import UIKit

class TDDiscoverSearchView: UIView {
    
    //d.右边的约束
    @IBOutlet weak var textFieldRightCons: NSLayoutConstraint!
    //e.取消按钮
    @IBOutlet weak var cancelButton: UIButton!
    
    @IBOutlet weak var textField: UITextField!
    //a.从xib中加载view
    class func searchView() -> TDDiscoverSearchView {
        
        return NSBundle .mainBundle().loadNibNamed("TDDiscoverSearchView", owner: nil, options: nil).last as! TDDiscoverSearchView
        
    }
    
    
    //B.把🔍设置到textfield上,并设置总是显示的模式
    override func awakeFromNib() {
        textField.leftView = leftView
        textField.leftViewMode = .Always
    }
    
    
    //C.设置🔍的图片，不要离左边太近
    override func layoutSubviews() {
        super.layoutSubviews()
        leftView.frame.size = CGSize(width: frame.height, height: frame.height)
    }
    
    
    
    //c.设置textField的点击事件,点击时输入框缩小，有动画效果
    @IBAction func textFeildDidBegin(sender: UITextField) {
        
        // 要执行约束动画,分为两步
        //一、先更新约束
        //f.设置缩小的范围
        self.textFieldRightCons.constant = self.cancelButton.frame.width
        
        //二、调用layoutIfNeeded并且将其放在动画block中
        UIView.animateWithDuration(0.25) { () -> Void in
            //如果需要重新布局，立马执行
            sender.layoutIfNeeded()
        }
    }
    
    //g. 取消按钮的点击事件
    @IBAction func cancelButtonClick(sender: UIButton) {
        
        //textField的宽度回到开始时,带有动画效果(步骤如上)
        textFieldRightCons.constant = 0;
        UIView.animateWithDuration(0.25) { () -> Void in
            self.textField.layoutIfNeeded()
        }
        
        //退出键盘
        self.textField.resignFirstResponder()
        
    }
    
    //A.懒加载控件——设置🔍图标
    private lazy var leftView: UIImageView = {
        //设置内容图片
        let imageView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        
        //设置内容模式
        imageView.contentMode = .Center
        return imageView
        
    }()

}
